// enhanced main.dart - Cross-platform Markdown editor (desktop-first)
// Features added:
// - Save / Save As with explicit path selection on desktop using FilePicker.saveFile
// - Better "Markdown Tips" UI with cards
// - Drag & drop to open files (desktop) using `desktop_drop`
// - Attempt to open file passed as program argument when launched from OS
// - Improved UI with Google Fonts and Card-based layout

import 'dart:io';
import 'dart:typed_data';
import 'dart:convert';

import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:file_picker/file_picker.dart';
import 'package:file_saver/file_saver.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:desktop_drop/desktop_drop.dart';

void main(List<String> args) {
  // If the app is launched with a file path argument (dragging onto exe / open-with),
  // pass it into the app so it can open on startup.
  String? initialPath;
  try {
    if (!kIsWeb && args.isNotEmpty) {
      initialPath = args.first;
    }
  } catch (_) {
    initialPath = null;
  }

  runApp(MyApp(initialFilePath: initialPath));
}

class MyApp extends StatelessWidget {
  final String? initialFilePath;

  const MyApp({super.key, this.initialFilePath});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Markdown 编辑器',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        brightness: Brightness.light,
        scaffoldBackgroundColor: const Color(0xFFF6F7FB),
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.white,
          foregroundColor: Colors.black87,
          elevation: 1,
        ),
        textTheme: GoogleFonts.notoSansTextTheme(Theme.of(context).textTheme),
      ),
      home: MarkdownEditorPage(initialFilePath: initialFilePath),
    );
  }
}

class MarkdownEditorPage extends StatefulWidget {
  final String? initialFilePath;

  const MarkdownEditorPage({super.key, this.initialFilePath});

  @override
  State<MarkdownEditorPage> createState() => _MarkdownEditorPageState();
}

class _MarkdownEditorPageState extends State<MarkdownEditorPage> {
  final TextEditingController _controller = TextEditingController(
    text: '# 欢迎\n\n这是一个现代化的 Markdown 编辑器示例。\n\n- 左侧编辑\n- 右侧预览\n\n你可以打开 / 保存文件。',
  );

  String? _currentFilePath; // 如果通过「打开」打开了本地文件，会记录路径
  bool _isDragging = false;

  @override
  void initState() {
    super.initState();
    // 如果主程序传入了初始文件路径，尝试打开它
    if (widget.initialFilePath != null) {
      _tryOpenAtStartup(widget.initialFilePath!);
    }
  }

  Future<void> _tryOpenAtStartup(String path) async {
    try {
      final f = File(path);
      if (await f.exists()) {
        final content = await f.readAsString();
        setState(() {
          _controller.text = content;
          _currentFilePath = path;
        });
      }
    } catch (e) {
      debugPrint('startup open failed: $e');
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _newFile() {
    setState(() {
      _controller.clear();
      _currentFilePath = null;
    });
  }

  Future<void> _openFile() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['md', 'markdown', 'txt'],
      );
      if (result == null) return; // 取消
      final path = result.files.single.path;
      if (path == null) {
        // web 平台不会返回 path
        final bytes = result.files.single.bytes;
        if (bytes != null) {
          final content = utf8.decode(bytes);
          setState(() {
            _controller.text = content;
            _currentFilePath = null;
          });
        }
        return;
      }

      final f = File(path);
      final content = await f.readAsString();
      setState(() {
        _controller.text = content;
        _currentFilePath = path;
      });
    } catch (e) {
      debugPrint('openFile error: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('打开文件失败：$e')));
      }
    }
  }

  Future<String?> _askFileName({String initial = 'untitled'}) async {
    return showDialog<String>(
      context: context,
      builder: (ctx) {
        final tc = TextEditingController(text: initial);
        return AlertDialog(
          title: const Text('保存为'),
          content: TextField(
            controller: tc,
            autofocus: true,
            decoration: const InputDecoration(hintText: '请输入文件名（不带扩展名）'),
            onSubmitted: (_) => Navigator.of(ctx).pop(tc.text.trim()),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(ctx).pop(),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.of(ctx).pop(tc.text.trim()),
              child: const Text('保存'),
            ),
          ],
        );
      },
    );
  }

  /// 保存文件：如果已有文件路径且不是 saveAs -> 覆盖本地文件；否则弹出保存对话并用 file_saver 处理跨平台保存
  Future<void> _saveFile({bool saveAs = false}) async {
    try {
      // 1) 如果已经通过“打开”拿到了本地 path，并且不是显式 saveAs，则直接覆盖
      if (!saveAs && _currentFilePath != null && !kIsWeb) {
        final f = File(_currentFilePath!);
        await f.writeAsString(_controller.text);
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('已覆盖保存到原路径')));
        }
        return;
      }

      // 2) 桌面：使用 FilePicker.saveFile 让用户选择目录与文件名
      if (!kIsWeb) {
        final suggested =
            _currentFilePath != null
                ? _currentFilePath!.split(Platform.pathSeparator).last
                : 'untitled.md';

        final savePath = await FilePicker.platform.saveFile(
          dialogTitle: '选择保存位置',
          fileName: suggested,
          type: FileType.custom,
          allowedExtensions: ['md'],
        );

        if (savePath == null) return; // 用户取消

        final f = File(savePath);
        await f.writeAsString(_controller.text);
        setState(() => _currentFilePath = savePath);

        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('已保存：$savePath')));
        }

        return;
      }

      // 3) Web：使用 file_saver
      final fileName = await _askFileName(initial: 'untitled');
      if (fileName == null || fileName.trim().isEmpty) return;

      final Uint8List bytes = Uint8List.fromList(utf8.encode(_controller.text));
      final savedPath = await FileSaver.instance.saveFile(
        name: fileName,
        bytes: bytes,
        fileExtension: 'md',
        mimeType: MimeType.other,
        customMimeType: 'text/markdown',
      );

      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('已保存：$savedPath')));
      }
    } catch (e) {
      debugPrint('saveFile error: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('保存失败：$e')));
      }
    }
  }

  void _showMarkdownTips() {
    showDialog(
      context: context,
      builder:
          (_) => AlertDialog(
            title: Row(
              children: const [
                Icon(Icons.menu_book_outlined),
                SizedBox(width: 8),
                Text('Markdown 常用语法'),
              ],
            ),
            content: SizedBox(
              width: 520,
              child: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    _buildTip('加粗', '**内容**', example: '**粗体**'),
                    _buildTip('斜体', '*内容*', example: '*斜体*'),
                    _buildTip('标题', '# 一级标题', example: '# 一级标题'),
                    _buildTip('引用', '> 引用内容', example: '> 这是一段引用'),
                    _buildTip('无序列表', '- 项目', example: '- 第一项\n- 第二项'),
                    _buildTip('有序列表', '1. 第一项', example: '1. 第一\n2. 第二'),
                    _buildTip(
                      '代码块',
                      '```\n代码\n```',
                      example: '```dart\nprint("Hi")\n```',
                    ),
                    _buildTip(
                      '链接',
                      '[文本](https://...)',
                      example: '[OpenAI](https://openai.com)',
                    ),
                    _buildTip(
                      '图片',
                      '![alt](https://...)',
                      example: '![logo](https://example.com/logo.png)',
                    ),
                  ],
                ),
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('关闭'),
              ),
            ],
          ),
    );
  }

  Widget _buildTip(String title, String syntax, {String? example}) {
    return Card(
      margin: const EdgeInsets.symmetric(vertical: 6),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      elevation: 1,
      child: ListTile(
        title: Text(title, style: const TextStyle(fontWeight: FontWeight.w700)),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 6),
            Text(syntax, style: const TextStyle(fontFamily: 'monospace')),
            if (example != null) ...[
              const SizedBox(height: 8),
              Text(
                '示例：',
                style: TextStyle(color: Colors.grey.shade700, fontSize: 12),
              ),
              SizedBox(height: 4),
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Text(
                  example,
                  style: const TextStyle(fontFamily: 'monospace'),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildEditor() {
    return Card(
      margin: const EdgeInsets.all(12),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: TextField(
          controller: _controller,
          keyboardType: TextInputType.multiline,
          maxLines: null,
          expands: true,
          style: GoogleFonts.firaCode(fontSize: 14),
          decoration: const InputDecoration(
            border: InputBorder.none,
            hintText: '在此输入 Markdown 内容...',
          ),
          onChanged: (_) => setState(() {}),
        ),
      ),
    );
  }

  Widget _buildPreview() {
    return Card(
      margin: const EdgeInsets.all(12),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Markdown(
          data: _controller.text,
          selectable: true,
          styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context)).copyWith(
            p: const TextStyle(fontSize: 15, height: 1.5),
            h1: const TextStyle(fontSize: 26, fontWeight: FontWeight.w700),
            h2: const TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget body = Row(
      children: [
        // 编辑区
        Expanded(flex: 1, child: _buildEditor()),

        // 分隔
        Container(width: 1, color: Colors.grey.shade200),

        // 预览区
        Expanded(flex: 1, child: _buildPreview()),

        // 右侧窄栏
        Container(
          width: 56,
          color: Colors.grey.shade100,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconButton(
                icon: const Icon(Icons.help_outline),
                tooltip: '语法提示',
                onPressed: _showMarkdownTips,
              ),
              const SizedBox(height: 6),
              IconButton(
                icon: const Icon(Icons.open_in_new),
                tooltip: '打开',
                onPressed: _openFile,
              ),
            ],
          ),
        ),
      ],
    );

    // 如果桌面环境，则包裹 DropTarget 支持拖入文件
    if (!kIsWeb &&
        (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
      body = DropTarget(
        onDragDone: (detail) async {
          if (detail.files.isNotEmpty) {
            final path = detail.files.first.path;
            if (path != null) {
              try {
                final f = File(path);
                if (await f.exists()) {
                  final content = await f.readAsString();
                  setState(() {
                    _controller.text = content;
                    _currentFilePath = path;
                  });
                }
              } catch (e) {
                debugPrint('drop open failed: $e');
              }
            }
          }
        },
        onDragEntered: (detail) => setState(() => _isDragging = true),
        onDragExited: (detail) => setState(() => _isDragging = false),
        child: Stack(
          children: [
            body,
            if (_isDragging)
              Positioned.fill(
                child: Container(
                  color: Colors.blue.withOpacity(0.08),
                  child: Center(
                    child: Card(
                      elevation: 6,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(12),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: const [
                            Icon(Icons.upload_file, size: 28),
                            SizedBox(width: 8),
                            Text('释放以打开文件'),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
          ],
        ),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('Markdown 编辑器'),
        actions: [
          IconButton(
            icon: const Icon(Icons.note_add),
            tooltip: '新建',
            onPressed: _newFile,
          ),
          IconButton(
            icon: const Icon(Icons.folder_open),
            tooltip: '打开',
            onPressed: _openFile,
          ),
          IconButton(
            icon: const Icon(Icons.save),
            tooltip: '保存',
            onPressed: () => _saveFile(saveAs: false),
          ),
          IconButton(
            icon: const Icon(Icons.save_as),
            tooltip: '另存为',
            onPressed: () => _saveFile(saveAs: true),
          ),
        ],
      ),
      body: body,
    );
  }
}
